package com.li.service;
import com.common.util.IdWorker;
import com.li.dao.UserMapper;
import com.li.model.User;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper mapper;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Optional<List<User>> queryAllUser() {
        List<User> users = mapper.queryAllUser();
        if(CollectionUtils.isEmpty(mapper.queryAllUser())){
            return Optional.empty();
        }
        return Optional.of(users);
    }

    @Override
    public Optional<User> queryUserByName(String name) {
        User user = mapper.queryUserByName(name);
        if (user == null){
            return Optional.empty();
        }
        return Optional.of(user);
    }

    @Override
    public String getUserPosition(long grade) {
        return mapper.getUserPosition(grade);
    }

    @Override
    public Optional<User> login(String name, String password) {
        User user = mapper.login(name,password);

        if (user == null){
            return Optional.empty();
        }
        if (user.getIsDeleted()==1){
            return Optional.empty();
        }
        user.setLastLogin(new Date());
        mapper.updateUser(user);
        return Optional.of(user);
    }
    @Override
    public int addUser(User user) {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (session.getAttribute("USER_SESSION")==null){
            user.setGrade(3);
        }
        if (user.getCreateTime() ==null){
            user.setCreateTime(new Date());
        }

        user.setIsDeleted(0);
        user.setId(idWorker.nextId());
        user.setLastLogin(new Date());
        return mapper.addUser(user);
    }

    @Override
    public Optional<User> queryUserById(long id) {
        User user = mapper.queryUserById(id);
        if (user ==null) {
            return Optional.empty();
        }
        return Optional.of(user);
    }

    @Override
    public int updateUser(User user) {
        return mapper.updateUser(user);
    }

    @Override
    public int deleteUser(long id) {
        return mapper.deleteUser(id);
    }
}
